package com.cms.clash.controller;


import cn.hutool.http.HtmlUtil;
import com.cms.clash.dto.ArcQueryDTO;
import com.cms.clash.dto.ArcShowDTO;
import com.cms.clash.dto.TreeNode;
import com.cms.clash.entity.ArchiveTypeEntity;
import com.cms.clash.entity.HostEntity;
import com.cms.clash.service.impl.ArchiveService;
import com.cms.clash.service.impl.ArchiveTypeService;
import com.cms.clash.util.CacheUtils;
import com.cms.clash.util.TemplateUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * IndexController
 * @author cms
 * @version 1.0.0
 * @date 2024/7/28
*/

@Controller
public class IndexController {
    @Autowired
    private ArchiveTypeService typeService;

    @Autowired
    private ArchiveService archiveService;

    @Autowired
    private CacheUtils cacheUtils;

    @RequestMapping("/")
    public String index(Model model) {
        // 公共导航
        setSiteInfoMap(model);

        // 文章列表
        List<ArcShowDTO> arcList = cacheUtils.getArcList(0, 10, null, "aid desc");
        List<ArcShowDTO> hotArcList = cacheUtils.getArcList(0, 10, null, "click desc");
        List<ArcShowDTO> randArcList = cacheUtils.getArcList(0, 5, null, "rand()");
        List<HostEntity> hostList = cacheUtils.getHostList(10);
        model.addAttribute("arcList", arcList);
        model.addAttribute("hotList", hotArcList);
        model.addAttribute("randList", randArcList);
        model.addAttribute("hostList", hostList);
        return TemplateUtil.TEMPLATE_INDEX;
    }


    @RequestMapping({"/search", "/search/{page}"})
    public String search(@PathVariable(name = "page", required = false) Integer page,Model model, HttpServletRequest request) {
        // 设置公共信息
        setSiteInfoMap(model);

        String keyWord = request.getParameter("s");
        keyWord = (keyWord.length() > 20) ? keyWord.substring(0, 20) : keyWord;
        keyWord = HtmlUtil.filter(keyWord);
        Integer pageIndex = 1;
        Integer pageSize = 10;
        pageIndex = (null != page && page.intValue() > pageIndex.intValue()) ? page : pageIndex;
        Integer totalCount = cacheUtils.queryArcListSearchCount(null, null, keyWord);
        Integer maxPage = ((totalCount % pageSize) == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        String pageText = TemplateUtil.getPageText( "/search/@pageNum?s="+keyWord, pageIndex, pageSize, totalCount);
        model.addAttribute("pageText", pageText);

        // 文章列表,右侧数据
        List<ArcShowDTO> arcList = new ArrayList<>();
        if (pageIndex <= maxPage) {
            ArcQueryDTO queryDTO = new ArcQueryDTO();
            queryDTO.setKeyWord(keyWord);
            queryDTO.setPageIndex(pageIndex);
            queryDTO.setPageSize(pageSize);
            arcList = archiveService.queryArcListSearch(queryDTO);
        }
        List<ArcShowDTO> hotArcList = cacheUtils.getArcList(0, 11, null, "click desc");
        List<ArcShowDTO> randArcList = cacheUtils.getArcList(0, 6, null, "rand()");
        List<HostEntity> hostList = cacheUtils.getHostList(10);

        model.addAttribute("arcList", arcList);
        model.addAttribute("hotList", hotArcList);
        model.addAttribute("randList", randArcList);
        model.addAttribute("hostList", hostList);
        model.addAttribute("keyword", keyWord);
        return TemplateUtil.TEMPLATE_SEARCH;
    }

    /**
     * 列表与分页
     * @param path
     * @param page
     * @param model
     * @return
     */
    @RequestMapping({"/{path}", "/{path}/{page}"})
    public String list(@PathVariable("path") String path, @PathVariable(name = "page", required = false) Integer page, Model model) {
        // 设置公共信息
        setSiteInfoMap(model);
        // 处理路径
        path = HtmlUtil.filter(path);
        path = (path.length() > 20) ? path.substring(0, 20) : path;
        path = "/" + path;
        Map<String, Integer> typePathMap = typeService.getTypePathMap();
        if (!typePathMap.containsKey(path)) {
            return TemplateUtil.TEMPLATE_PAGE404;
        }

        // 处理页数,计算可用最大页数
        Integer typeId = typePathMap.get(path).intValue();
        Integer pageIndex = 1;
        Integer pageSize = 10;
        pageIndex = (null != page && page.intValue() > pageIndex.intValue()) ? page : pageIndex;
        Integer totalCount = cacheUtils.queryArcListSearchCount(typeId, null, null);
        Integer maxPage = ((totalCount % pageSize) == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        String pageText = TemplateUtil.getPageText(path + "/@pageNum", pageIndex, pageSize, totalCount);
        model.addAttribute("pageText", pageText);

        // 当前分类
        Map<Integer, ArchiveTypeEntity> allNavMap = typeService.getAllNavMap();
        ArchiveTypeEntity currentType = allNavMap.get("k" + typeId);

        // 文章列表,右侧数据
        List<ArcShowDTO> arcList = new ArrayList<>();
        if (pageIndex <= maxPage) {
            ArcQueryDTO queryDTO = new ArcQueryDTO();
            queryDTO.setTypeId(typeId);
            queryDTO.setPageIndex(pageIndex);
            queryDTO.setPageSize(pageSize);
            arcList = archiveService.queryArcListSearch(queryDTO);
        }
        List<ArcShowDTO> hotArcList = cacheUtils.getArcList(0, 10, null, "click desc");
        List<ArcShowDTO> randArcList = cacheUtils.getArcList(0, 5, null, "rand()");
        List<HostEntity> hostList = cacheUtils.getHostList(10);

        model.addAttribute("currentTypeName", currentType.getTypeName());
        model.addAttribute("currentTypeLink", currentType.getTypeLink());
        model.addAttribute("arcList", arcList);
        model.addAttribute("hotList", hotArcList);
        model.addAttribute("randList", randArcList);
        model.addAttribute("hostList", hostList);
        return TemplateUtil.TEMPLATE_LIST;
    }

    /**
     * 详情页面
     * @param uuid
     * @param model
     * @return
     */
    @RequestMapping("/info/{uuid}.html")
    public String info(@PathVariable("uuid") String uuid, Model model) {
        setSiteInfoMap(model);

        uuid = HtmlUtil.filter(uuid);
        if (StringUtils.isEmpty(uuid)) {
            return TemplateUtil.TEMPLATE_PAGE404;
        }
        if (uuid.length() > 8) {
            uuid = uuid.substring(0, 8);
        }

        // 获取详情和其他列表
        ArcShowDTO detail = archiveService.queryArcByUuid(uuid);
        List<ArcShowDTO> hotArcList = cacheUtils.getArcList(detail.getTypeId(), 9, null, "click desc");
        List<ArcShowDTO> randArcList = cacheUtils.getArcList(0, 6, null, "rand()");
        List<ArcShowDTO> releaseArcList = cacheUtils.getArcList(0, 10, null, "rand()");
        List<HostEntity> hostList = cacheUtils.getHostList(10);

        String tpl = "<p><strong>@name:</strong><a href=\"@link\" target=\"_blank\" rel=\"noopener\">@link</a></p>";


        // 上一篇和下一篇
        Map<String, ArcShowDTO> prevAndNextMap = archiveService.queryArcPrevAndNext(detail.getAid(), detail.getTypeId());
        model.addAttribute("detail", detail);
        model.addAttribute("hotList", hotArcList);
        model.addAttribute("randList", randArcList);
        model.addAttribute("releaseList", releaseArcList);
        model.addAttribute("hostList", hostList);
        model.addAttribute("prevArc", prevAndNextMap.get("prev"));
        model.addAttribute("nextArc", prevAndNextMap.get("next"));
        return TemplateUtil.TEMPLATE_DETAIL;
    }


    /**
     * 设置公共信息
     * @param model
     */
    private void setSiteInfoMap(Model model) {
        List<TreeNode> navList = typeService.getAllNavTree();
        model.addAttribute("navList", navList);
        model.addAttribute("site_title_simple", "免费clash节点|科学上网");
        model.addAttribute("site_title", "免费clash节点|科学上网 - 免费公益SSR/V2ray/Shadowrocket/Clash节点/小火箭订阅链接|科学上网|免费梯子");
        model.addAttribute("site_keywords", "clash节点,小火箭,免费节点,科学上网,免费梯子,免费clash节点,免费加速器,clash for windows,clash免费节点,clash github");
        model.addAttribute("site_description", "免费公益SSR/V2ray/Shadowrocket/Clash节点/小火箭订阅链接|科学上网|免费梯子");
    }

}
